package section3_5;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * Created by Hyman on 2017/6/4.
 */
public class Searcher implements Runnable {

    /**
     * 开始查找的行数
     */
    private int firstRow;
    /**
     * 最后查找的行数（不包含）
     */
    private int lastRow;

    /**
     * 矩阵模拟对象
     */
    private MatrixMock mock;

    /**
     * 结果对象
     */
    private Results results;

    /**
     * 要查找的数字
     */
    private int number;

    private final CyclicBarrier cyclicBarrier;

    public Searcher(int firstRow, int lastRow, MatrixMock mock, Results results, int number, CyclicBarrier cyclicBarrier) {
        this.firstRow = firstRow;
        this.lastRow = lastRow;
        this.mock = mock;
        this.results = results;
        this.number = number;
        this.cyclicBarrier = cyclicBarrier;
    }

    /**
     * 核心方法，查找指定行数范围内的指定数字，将结果保存在结果数组对应的位置
     */
    @Override
    public void run() {
        int counter;
        System.out.printf("%s: Processing lines from %d to %d.\n", Thread.currentThread().getName(), firstRow, lastRow);

        for(int i=firstRow; i < lastRow; i++) {
            int row[] = mock.getRow(i);
            counter = 0;
            for(int j=0; j<row.length; j++) {
                if(row[j] == number) {
                    counter++;
                }
            }
            results.setData(i, counter);
        }

        System.out.printf("%s: Lines processed.\n", Thread.currentThread().getName());

        try {

            /**
             * 每一个线程到达集合点后就会调用await()方法通知CyclicBarrier对象,
             * CyclicBarrier对象会让这个线程休眠直到其他所有的线程都到达集合点。
             */
            cyclicBarrier.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (BrokenBarrierException e) {
            e.printStackTrace();
        }
    }

}
